package com.tal.live.interceptor;

import com.tal.live.utils.trace.TraceIdConfig;
import com.tal.live.utils.validator.StringHelper;
import com.tal.live.utils.web.WebHelper;
import org.slf4j.MDC;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 日志打印 pid requestId version 版本字段
 *
 * @author xianliru@100tal.com
 * @version 1.0
 * @createDate 2019/10/09 17:45
 */
@Configuration
public class LogbackInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestId = request.getHeader(TraceIdConfig.REQUEST_ID_KEY);
        String traceId = TraceIdConfig.traceId();
        if(StringHelper.isNotBlank(requestId)){
            traceId = StringHelper.isBlank(requestId)? UUID.randomUUID()
                    .toString()
                    :requestId;
        }
        String projectPid = TraceIdConfig.getProjectPid();
        MDC.put(TraceIdConfig.PROJECT_PID,projectPid);
        MDC.put(TraceIdConfig.REQUEST_ID_KEY,traceId);
        MDC.put(TraceIdConfig.ADDRESS_IP, WebHelper.getRemoteAddr());
        MDC.put(TraceIdConfig.PROJECT_VERSION,TraceIdConfig.getProjectVersion());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.clear();
    }
}
